//
//  ChartAdapterView.swift
//  TimeBoat
//
//  Created by bo wang on 2022/8/27.
//  Copyright © 2022 Time Boat. All rights reserved.
//

import UIKit
import Charts

/// 这个View作为各种ChartView的容器，根据外部指定的Chart类型创建和添加ChartView。
class ChartAdapterView: UIView {

    private(set) var line: NormalLineChartView?
    private(set) var bar: NormalBarChartView?
    private(set) var viewType: ChartViewType?
    var cur: BarLineChartViewBase? {
        switch viewType {
        case .line: return line
        case .bar: return bar
        case .none: return nil
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        backgroundColor = .clear
    }
    
    func using(chart type: ChartViewType) {
        self.viewType = type
        
        switch type {
        case .line:
            enableLineChartView()
            disableBarChartView()
        case .bar:
            enableBarChartView()
            disableLineChartView()
        }
    }
    
    private func enableLineChartView() {
        guard line == nil else { return }
        
        let view = NormalLineChartView(frame: bounds)
        addChartView(view)
        line = view
    }
    
    private func disableLineChartView() {
        line?.removeFromSuperview()
        line = nil
    }
    
    private func enableBarChartView() {
        guard bar == nil else { return }
        
        let view = NormalBarChartView(frame: bounds)
        addChartView(view)
        bar = view
    }
    
    private func disableBarChartView() {
        bar?.removeFromSuperview()
        bar = nil
    }
    
    private func addChartView(_ view: UIView) {
        addSubview(view)
        view.translatesAutoresizingMaskIntoConstraints = false
        addConstraints([
            topAnchor.constraint(equalTo: view.topAnchor),
            leadingAnchor.constraint(equalTo: view.leadingAnchor),
            bottomAnchor.constraint(equalTo: view.bottomAnchor),
            trailingAnchor.constraint(equalTo: view.trailingAnchor)
        ])
        layoutIfNeeded()
    }
}
